
import {
  getToken,
  setToken,
  removeToken,
  getAccount,
  setAccount,
  removeAccount,
  getName,
  setName,
  removeName,
  getUid,
  setUid,
  removeUid,
} from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    account: getAccount(), // 用户名
    name: getName(), // 姓名
    uid: getUid()// uid
  }
}
const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, {
      token: '',
      account: '', // 用户名
      name: '', // 姓名
      uid: ''// uid
    })
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ACCOUNT: (state, account) => {
    state.account = account
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_UID: (state, uid) => {
    state.uid = uid
  },
}
const actions = {
  // 用户登录
  // login({ commit }, userInfo) {
  //   return new Promise((resolve, reject) => {
  //     login(...userInfo).then(response => {
  //       console.log(response)
  //       const data = response.data
  //       dispatch.saveMsg({ commit }, data)
  //       resolve()
  //     }).catch(error => {
  //       reject(error);
  //     })
  //   })
  // },

  // 用户退出登录
  logout({ commit }) {
    removeToken()
    removeAccount()
    removeName()
    removeUid()
    commit('RESET_STATE');
  },

  // 登录或注册后保存信息
  saveMsg({ commit }, data) {
    commit('SET_TOKEN', data.token);
    commit('SET_ACCOUNT', data.account);
    commit('SET_NAME', data.name);
    commit('SET_UID', data.uid);
    setToken(data.token);
    setAccount(data.account);
    setName(data.name);
    setUid(data.uid);
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

